import uuid from 'uuid'
import {keyEmpowerTally} from "@/api/confidentialityOfficer/hostEmpower";
import Cookies from 'js-cookie'

export let Socket = ''
let setIntervalWesocketPush = null
let socketPending = true;
window.websocketUrl =  "ws://192.168.1.29:9010"
window.websocketProduct =  "hongke_product_mgxx"
// AA01（Key AA授权点数配置文件）
window.keyAuthorizedPointsFileName = "AA01.hkxdr"

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = () => {
  Socket && Socket.close()
  if (!Socket) {
    // console.log('建立websocket连接')
    Socket = new WebSocket(window.websocketUrl)
    Socket.onopen = onopenWS
    Socket.onmessage = onmessageWS
    Socket.onerror = onerrorWS
    Socket.onclose = oncloseWS
    setTimeout(() => {
      if (Socket.readyState === 0 && socketPending) {
        socketPending = false;
        SocketError()
      }
    }, 1000)
  } else {
    // console.log('websocket已连接')
  }
}

/**打开WS之后发送心跳 */
const onopenWS = () => {
  //sendPing()
  sendKeyOnline()
}

/**连接失败重连 */
const onerrorWS = () => {
  Socket.close()
  clearInterval(setIntervalWesocketPush)
  // console.log('连接失败重连中')
  if (Socket.readyState !== 3) {
    Socket = null
    // createSocket()
    SocketError()
  }
}

/**WS数据接收统一处理 */
const onmessageWS = e => {
  window.dispatchEvent(new CustomEvent('onmessageWS', {
    detail: {
      data: e.data
    }
  }))
}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = message => {
  // setTimeout(() => {
    if (Socket.readyState === 0) {
      connecting(message)
    } else {
      Socket.send(JSON.stringify(message))
    }
  // }, 1000)
}

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = message => {
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close()
    // createSocket()
    SocketError()
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(message))
  } else if (Socket.readyState === 0) {
    connecting(message)
  }
}

/**断开重连 */
const oncloseWS = () => {
  clearInterval(setIntervalWesocketPush)
  // console.log('websocket已断开')
  if (Socket.readyState !== 2) {
    Socket = null
    // createSocket()
    SocketError()
  }
}


/**
 * websocket链接失败时提示
 * @constructor
 */
const SocketError = () => {

}

/**发送命令--检测key是否插入使用
 * @param {number} time 间隔毫秒 默认5000
 */
export const sendKeyOnline = (time = 30000) => {
  clearInterval(setIntervalWesocketPush)
  sendKeyScan()
  setIntervalWesocketPush = setInterval(() => {
    sendKeyScan()
  }, time)
}

/**
 * 接收消息--控制插key操作
 */

const getSocketData = e => {  // 创建接收消息函数
    const data = e && eval('(' + e.detail.data + ')');
    let resultData = data.result_data;
    //查询key序列号
    if (data.cmd_name === "key_scan") {
      //key初始化授权点,是否已授权
      let keyEmpower = Cookies.get("keyEmpower")
      if(resultData.key_sn && !keyEmpower){
        //查询配置文件
        let cmdData = {"key_sn": resultData.key_sn,"file_name":window.keyAuthorizedPointsFileName}
        sendKeyProduct("key_read_file", cmdData)
      }
    }
    //读取文件
    if (data.cmd_name === "key_read_file") {
      if (0 === data.err_code) {
        if(resultData.read_data){
          keyEmpowerTally(resultData.read_data).then((res) => {
            Cookies.set('keyEmpower', res)
          })
        }
      }
    }

}

/**
 * key业务发送指令--通用--获取key号
 */
const sendKeyScan = () => {
  let sendKeyData = {}
  sendKeyData.cmd_sender = "hongke_product_common"
  sendKeyData.cmd_id = uuid.v4()
  sendKeyData.cmd_name = "key_scan"
  sendKeyData.cmd_data = {}
  sendWSPush(sendKeyData)
}
/**
 * key业务发送指令--已定义产品
 */
const sendKeyProduct = (cmdName, cmdData) => {
  let sendKeyData = {}
  sendKeyData.cmd_sender = window.websocketProduct
  sendKeyData.cmd_id = uuid.v4()
  sendKeyData.cmd_name = cmdName
  sendKeyData.cmd_data = cmdData
  sendWSPush(sendKeyData)
}

export default {
  createSocket,sendWSPush,getSocketData,sendKeyProduct
}
